import { ProductCreateComponent } from './../product-create/product-create.component';
import { ModalService } from '@app/shared/utils'
import { ApiService } from '../../services/api.service'
import {ActivatedRoute, Router} from '@angular/router'
import { QlMessageService } from 'qloud-angular'
import {Component, OnInit, Output, ViewChild, ViewContainerRef} from '@angular/core'
import { FormGroup, FormBuilder } from '@angular/forms'
import { NetService, PageService } from '@app/core/http'
import { TagComponent } from '../../components/tag/tag.component'
import { SelectCustomerComponent } from '../../components/select-customer/select-customer.component'
import { SelGroupComponent } from '../../components/sel-group/sel-group.component'
import { SelectPruductComponent } from '../../components/select-pruduct/select-pruduct.component'
import {CursorService} from "@core/http/cursor.service";
import {DatePipe, formatDate} from "@angular/common";


@Component({
  selector: 'app-combo-create',
  templateUrl: './combo-create.component.html',
  styleUrls: ['./combo-create.component.scss'],
  providers: [ModalService, PageService,ApiService,DatePipe]
})
export class ComboCreateComponent implements OnInit {
  id = '';
  groupname = '';//产品组合名称
  groupcode = '';//产品组合编码
  desc = '';//产品组合介绍
  expectminratio = '';//预期利率
  rangenotes = '';//适用范围
  agreement = '';//办理规定
  attentionnotes = '';//注意事项
  public customerList = [];
  public customerTag = [];
  public customerGroup = [];
  public productList = [];
  public groupData = [];
  // public catalogList = [{catalogname: '', catalogno: '', contents: []}];
  catalogList :any=[];
  public delCatalogList =[];
  public catalogList2 =[];
  constructor(
    private fb: FormBuilder,
    public modal: ModalService,
    public pageService: PageService,
    private message: QlMessageService,
    private apiService: ApiService,
    private router: Router,
    private route: ActivatedRoute,
    public cursorService: CursorService,
    private datePipe: DatePipe,
  ) {
  }

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id');
    if (this.id != ''&&this.id!=null) {
      this.apiService.getcomboDetail(this.id).subscribe(data => {
        this.groupname = data.groupname;
        this.groupcode = data.groupcode
        this.desc = data.desc
        this.expectminratio = data.expectminratio
        this.rangenotes = data.rangenotes
        this.agreement = data.agreement
        this.attentionnotes = data.attentionnotes
      });
      this.cursorService.limit = 100;
      this.cursorService.statement = "select * where groupcode=" + "'" + this.id + "'";
      this.apiService.getproductNum(this.cursorService).subscribe(data => {
         console.log('data:'+JSON.stringify(data))
        let contents =[];
        for(let item of data){
          this.delCatalogList.push(item['rowcode']);
          for(let item2 of item['contents']){
            item2['catalogname'] =item['catalogname']
            item2['catalogno'] =item['catalogno']
            contents.push(item2)

          }

        }
        this.productList = contents;
        console.log('----------delCatalogList:'+JSON.stringify(this.delCatalogList))
        console.log('----------productList:'+JSON.stringify(this.productList))
        this.getcatalog();
      })

    }
  }

  public getProductList() {
    this.apiService.getProductList().subscribe(data => {
      this.productList = data.splice(14, 3)
    })
  }

  public onSelectProduct() {
    // this.attrDialog = true;
    this.modal
      .open({
        title: '选择产品',
        size: 'huge',
        component: SelectPruductComponent
      }).subscribe(data => {
      let data2 = [];
      if (this.productList.length > 0) {
        for (let j = 0; j < data.length; j++) {
          let isrepeat = false;
          for (let k = 0; k < this.productList.length; k++) {
            if (data[j]['productcode'] === this.productList[k]['productcode']) {
              this.productList[k]['count'] += 1;
              isrepeat = true;
              break;
            }
          }
          if (isrepeat) {
            continue;
          } else {
            data2.push(data[j])
          }
        }
        this.productList = this.productList.concat(data2)
      } else {
        this.productList = this.productList.concat(data)
      }
     this.getcatalog();

    })

  }
  getcatalog(){
     console.log('productList:'+JSON.stringify(this.productList))
    for (let i = 0; i < this.productList.length; i++) {
      this.catalogList.push({
        catalogname: this.productList[i]['catalogname'],
        catalogno: this.productList[i]['catalogno'],
        contents: []
      })
    }
    console.log('this.catalogList1: ' + JSON.stringify(this.catalogList))
    this.catalogList = this.unique(this.catalogList);
    console.log('this.catalogList2: ' + JSON.stringify(this.catalogList))
    console.log('this.productList: ' + JSON.stringify(this.productList))
    for (let j = 0; j < this.catalogList.length; j++) {
      for (let k = 0; k < this.productList.length; k++) {
        if (this.catalogList[j]['catalogno'] === this.productList[k]['catalogno']) {
          let isrepeat =false
          for(let item of this.catalogList[j]['contents']){
            if(item['productcode']==this.productList[k]['productcode']){
              isrepeat = true
            }
          }
          if(!isrepeat){
            this.catalogList[j]['contents'].push(this.productList[k])
          }
          // this.catalogList[j]['contents'].push(this.productList[k])
        }
      }
    }
    console.log('this.catalogList3: ' + JSON.stringify(this.catalogList))

  }
  //目录列表去重
  unique(arr) {
    let result = [];
    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (!obj[arr[i]['catalogno']]) {
        result.push(arr[i]);
        obj[arr[i]['catalogno']] = true;
      }
    }
    return result;
  }

  findNum(arr) {
    let result = [];
    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (!obj[arr[i]['catalogNo']]) {
        result.push(arr[i]);
        obj[arr[i]['catalogNo']] = true;
      }
    }
    return result;
  }
   save(){
      if(this.id != ''&&this.id!=null){
        this.updateCombo()
      }else{
        this.creatCombo()
      }
   }
  delProduct(productcode){
    for(let i=0;i<this.productList.length;i++){
      if(this.productList[i]['productcode'] ==productcode){
        this.productList = this.productList.splice(i+1)
      }
      this.catalogList =[];
      if(this.productList.length>0){
        this.getcatalog();
      }
    }
  }
  public updateCombo(){
    let  date = new Date()
    let year = date.getFullYear();
    let month = date.getMonth();
    let dat = date.getDate();
    let createtime = year+'-'+month+'-'+dat
    let params = {
      grouptype: "组合类别",
      lastupdater: "yangkang",
      orgid: "dep_001",
      rangeorgid: "org_61040_01",
      customcontent: "{as}",
      marketingtemplateid: "营销模版id",
      groupname: this.groupname,
      groupcode: this.groupcode,
      desc: this.desc,
      expectminratio: this.expectminratio,
      expectmaxratio: 0.058,
      rangenotes: this.rangenotes,
      agreement: this.agreement,
      attentionnotes: this.attentionnotes,
      lastupdatetime: createtime,
      createuser: "yangkang",
      rangetype: "0",
      createtime: createtime,
    }
    this.apiService.updateGroup(params,this.id).subscribe(data => {
      this.message.success('修改成功');
      this.router.navigate(['/product/combo-list'])
    })
    console.log('this.catalogList:'+JSON.stringify(this.catalogList))
    // if(this.delCatalogList.length>0){
    //   for(let item of this.delCatalogList){
    //     this.apiService.delGroupProduct(item).subscribe(data => {
    //     })
    //   }
    // }
    // this.apiService.addGroupProduct(this.catalogList,this.id).subscribe(data => {
    //
    // })
    // // console.log('params:' + JSON.stringify(params))
    // this.apiService.updateGroup(params,this.id).subscribe(data => {
    //   this.message.success('修改成功');
    // })
  }
  public creatCombo() {
    let params = {
      grouptype: "组合类别",
      lastupdater: "yangkang",
      orgid: "dep_001",
      rangeorgid: "org_61040_01",
      customcontent: "{as}",
      marketingtemplateid: "营销模版id",
      groupname: this.groupname,
      groupcode: this.groupcode,
      desc: this.desc,
      expectminratio: this.expectminratio,
      expectmaxratio: 0.058,
      rangenotes: this.rangenotes,
      agreement: this.agreement,
      attentionnotes: this.attentionnotes,
      lastupdatetime: "2019-12-20",
      products: this.catalogList,
      createuser: "yangkang",
      rangetype: "0",
      createtime: "2019-12-20",
    }
    console.log('params:' + JSON.stringify(this.catalogList))
    // this.apiService.creatGroup(params).subscribe(data => {
    //   this.message.success('新增成功');
    //   this.router.navigate(['/product/combo-list'])
    // })
  }
}
